/*
 * Copyright (C) 2007 Evan Long    longx223 (at) umn (dot) edu
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/**
 * @file   framegrabber.c
 * @author Evan Long
 * 
 * @brief  Implementation of frame_grabber
 * 
 * 
 */

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <string.h>
#include <linux/types.h>
#include <linux/videodev.h>
#include "framegrabber.h"
#include "util.h"
#include "safe_malloc.h"

frame_grabber_t* new_frame_grabber(const char* device)
{
  int devfd;
  SYS_CALL((devfd = open(device, O_RDONLY)), "Opening device failed");

  struct video_capability vcap;
  SYS_CALL(ioctl(devfd, VIDIOCGCAP, &vcap), 
	   "Could not obtain device capabilities");

  frame_grabber_t* tmp = (frame_grabber_t*)safe_malloc(sizeof(
							 frame_grabber_t));
  tmp->device = (char*)safe_malloc(strlen(device)+1);
  strcpy(tmp->device, device);
  tmp->devfd = devfd;
  tmp->width = vcap.maxwidth;
  tmp->height = vcap.maxheight;
  /*By three because this is a 24 bit RGB image*/
  tmp->bufsize = 3 * tmp->width * tmp->height;
  tmp->buffer = (unsigned char*)safe_malloc(tmp->bufsize);

  return tmp;
}

unsigned char* grab_frame(frame_grabber_t* fgt)
{
  SYS_CALL(read(fgt->devfd, fgt->buffer, fgt->bufsize), 
	   "Reading image from device failed");

  return fgt->buffer;
}

void free_frame_grabber(frame_grabber_t* fgt)
{
  free(fgt->device);
  close(fgt->devfd);
  free(fgt->buffer);
  free(fgt);
}
